package com.learner.ucenter.controller.api;

import com.learner.common.util.JwtUtils;
import com.learner.pojo.user.UserSetting;
import com.learner.ucenter.service.UserSettingService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author ice2020x
 * @Date: 2023/2/2
 * @Description: 用户设置控制器
 **/
@RequestMapping("/api/ucenter/user/setting")
@RestController
public class UserSettingController {
    @Resource
    private UserSettingService userSettingService;

    /**
     * 获取当前用户设置
     *
     * @param request request
     * @return userSetting
     */
    @GetMapping("")
    public UserSetting getCurrentUserSetting(HttpServletRequest request) {
        String userId = JwtUtils.getCurrentUserId(request);
        UserSetting userSetting = userSettingService.findByUserId(userId);
        if (userSetting == null) {
            // 当前用户没有对应的用户设置数据
            UserSetting newSetting = new UserSetting();
            newSetting.setUserId(userId);
            userSettingService.save(newSetting);
            return newSetting;
        }
        return userSetting;
    }

    /**
     * 更新当前用户设置
     *
     * @param userSetting setting
     * @return UserSetting
     */
    @PutMapping("/update")
    public UserSetting updateCurrentUserSetting(@RequestBody UserSetting userSetting, HttpServletRequest request) {
        String userId = JwtUtils.getCurrentUserId(request);
        UserSetting oldSetting = userSettingService.findByUserId(userId);
        if (oldSetting == null) {
            // 当前用户没有对应的用户设置数据
            userSetting.setUserId(userId);
            userSettingService.save(userSetting);
            return userSetting;
        }
        userSettingService.update(userSetting);
        return userSetting;
    }

}